<template>
  <div>
    <div class="main-head flex-between container-fluid">
      <div class="title">
        <h1 v-text="$t('pro.admin.ManageTransactions')"></h1>
      </div>
    </div>
    <div class="content container-fluid">
      <div class="portlet">
        <div class="tools grid transaction-grid">
          <a-form-item :label="$t('pro.admin.Searchuser')">
            <a-select
                :value="userByCompanyDefault"
                style="width: 100%;"
                showSearch
                @change="changeUserByCompany"
            >
              <a-select-option
                    v-for="(user, key) in userList"
                    :key="key"
                    :value="user.id"
              >{{user.msg}}</a-select-option>
            </a-select>

          </a-form-item>

          <a-form-item :label="$t('pro.admin.SelectDateRange')">
            <a-range-picker
              :format="dateFormat"
              showToday
              :defaultValue="[$moment(datePickerDefaultValue2[0], dateFormat),$moment(datePickerDefaultValue2[1], dateFormat)]"
              @change="handleDatePickerChange"
            />
          </a-form-item>

          <a-form-item :label="$t('pro.admin.TransactionType')">
            <a-select
              style="width: 100%"
              @change="handleChange"
              v-model="transactionType"
            >
              <a-select-option v-for="(item) in transactionTypes"  :key="item.key">{{ item.value }}</a-select-option>
            </a-select>
          </a-form-item>

          <div class="click-btn flex-direction-row">
            <a-form-item label="/" class="add-btn">
              <a-button type="primary" icon="search" @click="searchTransactions">{{ $t('pro.admin.Search') }}</a-button>
            </a-form-item>
            <a-form-item label="/" class="add-btn">
              <a-button type="primary" icon="dollar" @click="addTransaction">{{ $t('pro.admin.AddNewTransaction') }}</a-button>
            </a-form-item>
          </div>
        </div>

        <div>
          <template v-if="empty">
            <a-empty image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
              <span slot="description">Your search returns no results</span>
            </a-empty>
          </template>
          <!-- table列表 and 分页 -->
          <div v-else class="bottom-table-page">
            <!-- 表格数据 -->
            <a-table
                :columns="columns"
                :rowKey="record => record.id"
                :dataSource="dataList"
                :loading="listLoading"
                :pagination="false"
                :scroll="{ x: 1100 }"
            >
              <template slot="sta" slot-scope="sta">
                {{ status[sta || 0].value }}
              </template>

              <div slot="type" slot-scope="type">
                {{ $t('pro.AddTransactionID.methods').find(v => v.key == type).value || ' - ' }}
              </div>

              <template slot="name" slot-scope="text, record">
                {{ record.lastName }}&nbsp;{{ record.firstName }} # {{ text }}
              </template>

              <div slot="createdAt" slot-scope="createdAt">
                {{ createdAt | createdAtToDate}}
              </div>

            </a-table>
            <!-- 分页 -->
            <div class="public-page-box">
              <a-pagination
                  showSizeChanger
                  showQuickJumper
                  :pageSize.sync="pagination.pageSize"
                  :total="pagination.total"
                  v-model="pagination.current"
                  @change="onShowSizeChange"
                  @showSizeChange="onShowSizeChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getRecharge } from '../../api/sys-user-controller'
import { parseTime } from '../../utils/time'

export default {
  filters: {
      createdAtToDate(value) {
          return parseTime(value, '{y}-{m}-{d}')
      }
  },
  data() {
    return {
        userByCompanyDefault: " ",
        userId: "",
        dateFormat: 'YYYY-MM-DD',
        selectDate: [],
        transactionType: -1,
        empty: false,
        pagination: {
            pageSizeOptions: ['10', '20', '30', '40', '50'],
            current: 1,
            pageSize: 5,
            total: 50,
        },
        listLoading: false,
        dataList: [],
        types: [],
    }
  },
  methods: {
    //公用参数请求
    requestParams(){
        let params = {};
        if (this.transactionType != -1) {
            params.type = this.transactionType;
        }
        //如果用户没有选择就默认的
        if(this.selectDate.length <= 0) {
            params.start = parseTime(new Date(this.datePickerDefaultValue2[0]), '{y}-{m}-{d}');
            params.end = parseTime(new Date(this.datePickerDefaultValue2[1]), '{y}-{m}-{d}');
        }else {
            params.start = this.selectDate[0];
            params.end = this.selectDate[1];
        }
        params.start = params.start+ ' 00:00:00';
        params.end = params.end+ ' 23:59:59';
        params.page = this.pagination.current;
        params.results = this.pagination.pageSize;
        params.userId = this.userId;
        params = JSON.parse(JSON.stringify(params));
        return params
    },

    handleDatePickerChange(selectDate, dateFormat) {
        this.selectDate = dateFormat;
        console.log(this.selectDate);
    },

    searchTransactions() {
        //把组件得日期转成后端需要得
        this.fetch(this.requestParams())
    },

    handleChange() {
        console.log(this.transactionType);
    },

    addTransaction() {
      this.$router.push("/admin/edittransaction/0");
    },

    //监听分页的变化
    onShowSizeChange (page, pageSize) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.fetch(this.requestParams())
    },

    //table 表单拉取数据
    fetch (params = {results: 5,page: 1}) {
          //查询前开始动画
          this.listLoading = true;
          getRecharge(params).then(res => {
              let { code, data } = res.data || {};
              if (code == 200) {
                  this.dataList = data.records || [];
                  this.pagination.total = data.total
              }
              this.listLoading = false;
          }).catch(e =>{
              console.log(e);
              this.listLoading = false;
          });
      },

    changeUserByCompany(value) {
        this.userId = value.split(" ").pop();
        this.userByCompanyDefault = value
    }
  },
  computed: {
      // 用户需自定义日期期限时，DatePicker的默认值
      datePickerDefaultValue2() {
          const firstdate = this.$moment().subtract(7, 'days')
          const firstday = firstdate.hours(0).minutes(0).seconds(0).milliseconds(0)
          const lastday = this.$moment().endOf('day')
          return [firstday,lastday]
      },

    transactionTypes() {
       return this.$t('pro.admin.transactionTypes')
    },
    status() {
      return this.$t('pro.admin.status')
    },
    columns() {
        return this.$t('pro.transactionRecord.columns')
    },
    userByCompany() {
      return this.$store.getters.userByCompany || []
    },
    userList() {
          let list = this.userByCompany.map(company => {
              return {
                  id:`${company.company} | ${company.firstName} | ${
                      company.lastName
                      } | ${company.id}`,
                  msg: `${company.company} | ${company.firstName} | ${
                      company.lastName
                      } | ${company.id}`
              };
          });
        list.unshift({id: " ", msg: "ALL"})
        return list
    },
    methods() {
        return this.$t('pro.AddTransactionID.methods')
    },

  },
  created() {
    this.fetch(this.requestParams())
  }
}
</script>

<style lang="less">
  .add-btn {
    margin-right: 15px;
  }
.transaction-grid {
  grid-template-columns: 300px 350px 210px 210px 260px;
  padding-top: 15px;
  .ant-form-item-label {
    line-height: 1;
  }
  >div {
    margin-bottom: 0;
  }
}
@media screen and (max-width: 1350px) {
  .transaction-grid {
    grid-template-rows: auto auto;
    grid-template-columns: 300px 350px 210px 210px;
    :last-child {
      grid-row: 2;
      .ant-form-item-label {
        display: none;
      }
    }
  }
}
@media screen and (max-width: 1230px) {
  .transaction-grid {
    grid-template-rows: repeat(4,auto);
    grid-template-columns: 300px 350px;
    :nth-child(3) {
      grid-row: 2;
    }
    :nth-child(4) {
      grid-row: 3;
    }
    :last-child {
      grid-row: 4;

    }
  }
}
@media screen and (max-width: 1000px) {
  .transaction-grid {
    grid-template-rows: repeat(4,auto);
    grid-template-columns: 300px 350px;
    :nth-child(3) {
      grid-row: 2;
    }
    :nth-child(4) {
      grid-row: 3;
    }
    :last-child {
      grid-row: 4;

    }
  }
}
@media screen and (max-width: 768px) {
  .transaction-grid {
    grid-template-rows: repeat(5,auto);
    grid-template-columns: 300px;
    :nth-child(2) {
      grid-row: 2;
    }
    :nth-child(3) {
      grid-row: 3;
    }
    :nth-child(4) {
      grid-row: 4;
    }
    :last-child {
      grid-row: 5;
    }
  }
}
@media screen and (max-width: 640px) {
  .transaction-grid {
    grid-template-columns: 100%;
  }
}
</style>
